# -*- coding: utf-8 -*-
# 信息保存/删除/输出
import base64
import os
import sys
import re
import getpass
path = os.path.dirname(os.path.abspath(sys.argv[0]))

# 用于处理输入的数据格式
def cmd_format(lable, rule):
	while True:
		print('{} (<#q> exit):'.format(lable))
		if lable.strip().strip(':').upper() == 'PASSWORD':
			temp = getpass.getpass()
		else:
			temp = input().strip()
		content = re.match(r'{}'.format(rule), temp)
		if content:
			break
		elif 'port' in lable:
			temp = 22
			break
		elif temp.strip() == '#q':
			os.system('cls')
			break
		os.system('cls')
		print('[Warning]: Invalid format...')
	return temp


def about():
	f = open('{}/info/about.bat'.format(path))
	content = f.read()
	try:
		info = eval(content)
		os.system('cls')
		print('About SSH......')
		for k, v in info.items():
			print('{}: {}'.format(k, v))
	except:
		print('No Info......')
	f.close()
	return


# 添加主机信息
def add_host():
	print('Add host information......')
	print('[HELP]: INPUT <#q> exit...')
	# IP地址
	host_ip = cmd_format('Host IP:', '^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$')
	if host_ip == '#q':
		return True
	# 端口号
	host_port = cmd_format('Host port(Default 22):', '[0-9]+')
	if host_port == '#q':
		return True
	# 用户名
	username = cmd_format('User Name:', '^[^ ]+$')
	if username == '#q':
		return True
	# 密码
	password = cmd_format('Password:', '.*')
	if password == '#q':
		return True
	# password = base64.encodestring(password)
	# 输入别名
	alias = cmd_format('Local Alias:', '^[^ ]+$')
	if alias == '#q':
		return True
	elif not alias:
		os.system('cls')
		print('[Warning]: Alias cannot be empty...')
		return False
	# 查重
	f = open('{}/data/info.d'.format(path))
	hosts = f.readlines()
	for line in hosts:
		temp = line.strip('\n')
		if not temp:
			continue
		line_list = line.split(' ')
		if host_ip == line_list[0] and host_port == line_list[1]:
			os.system('cls')
			print('[Warning]: {}: {} existing...'.format(host_ip, host_port))
			return False
		if alias == line_list[4]:
			os.system('cls')
			print('[Warning]: Alias <{}> existing...'.format(alias))
			return False
	f.close()
	# 保存
	f = open('{}/data/info.d'.format(path), 'a')
	f.write('\n{} {} {} {} {}'.format(host_ip.strip('\n'), host_port, username.strip('\n'), password.strip('\n'), alias.strip('\n')))
	f.close()
	print('[INFO]:{} {}@{}:{} Add Successfully...'.format(alias.strip('\n'), username.strip('\n'), host_ip.strip('\n'), password.strip('\n')))
	return True


def add_hosts():
	while True:
		if add_host():
			break
		print('\n\nTry Again:')


# 删除主机信息
def remove_host():
	while True:
		f = open('{}/data/info.d'.format(path))
		hosts = f.readlines()
		f.close()
		hosts_len = len(hosts)
		if hosts_len < 1:
			os.system('cls')
			print('[Warning]: No host info...')
			return
		print('Remove host information......')
		print('%' * 40)
		print('FORMAT:\nAlias UserName@IP: PORT')
		print('%' * 40)
		hosts_temp = []
		n = 1
		for i in range(0, hosts_len):
			if not hosts[i].strip():
				continue
			line_list = hosts[i].strip().split(' ')
			print("<{}>: {} |{}@{}: {}|".format(n, line_list[4], line_list[2], line_list[0], line_list[1]))
			n += 1
			hosts_temp.append(hosts[i])
		hosts = hosts_temp[:]
		choice = input('[Remove]: Choose the Number or Alias(<#q> to exit):')
		is_alias = False
		is_num = False
		try:
			choice = int(choice)
			if choice < 1 or choice > hosts_len:
				os.system('cls')
				print('[Warning]:Number inexistence...')
				continue
			del hosts[choice-1]
			is_num = True
		except:
			is_alias = True
		if is_alias:
			if choice.strip() == '#q':
				os.system('cls')
				break
			n = 0
			for h in hosts:
				if choice.strip() == h.split(' ')[4].strip():
					del hosts[n]
					is_num = True
				n += 1
		if not is_num:
			os.system('cls')
			print('[Warning]:Alias inexistence...')
			continue
		else:
			choice = input('Remove?[y/n]:')
			if choice.strip().upper() == 'Y':
				f = open("{}/data/info.d".format(path), "w")
				for h in hosts:
					f.write(h)
				print('Remove Successfully...')
				f.close()